package com.exchange.used.service.impl;

import com.exchange.used.config.converters.LayuiResult;
import com.exchange.used.entity.Goods;
import com.exchange.used.entity.List;
import com.exchange.used.repository.GoodsRepository;
import com.exchange.used.repository.ListRepository;
import com.exchange.used.service.ListServiceI;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("ListService")
public class ListService implements ListServiceI {

    @Autowired
    ListRepository listRepository;
    @Autowired
    GoodsRepository goodsRepository;

    @Override
    public LayuiResult saveList(List list) {
        LayuiResult result = new LayuiResult();
        try {
            if(list == null || list.getFkgoodsid().isEmpty() || list.getFksaverid().isEmpty()){
                result.setCode(-1);
                result.setMsg("存在空数据");
                return result;
            }
            List tempList = listRepository.getListByFkgoodsidAndFksaverid(list.getFkgoodsid(), list.getFksaverid());
            Goods goods = goodsRepository.getGoodsByGoodsid(list.getFkgoodsid());
            if(goods == null){
                result.setCode(-1);
                result.setMsg("该商品不存在");
                return result;
            }
            if(goods.getFksellerid().equalsIgnoreCase(list.getFksaverid())){
                result.setCode(-1);
                result.setMsg("您不能将自己发布的商品加入购物车");
                return result;
            }

            if(tempList != null){
               tempList.setListnum(tempList.getListnum() + 1);
               tempList.setListtime(new Date());
               listRepository.save(tempList);
            }else{
                list.setListnum(1);
                list.setListtime(new Date());
                listRepository.save(list);
            }
            result.setMsg("已加入购物车");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Override
    public LayuiResult updateListNum(String value, String listid) {
        LayuiResult result = new LayuiResult();

        try {
            if(!StringUtils.isNumeric(value)){
                result.setCode(-1);
                result.setMsg("请填写有效的整数数字");
                return result;
            }
            listRepository.updateListNum(Integer.parseInt(value), listid);
            result.setMsg("数量更新成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
